package com.clsfd.ivr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.CharsetEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.JAXBException;
import com.clsfd.charging.ChargeEvent;
import com.clsfd.charging.ChargeStatus;
import com.clsfd.database.SystemParams;
import com.clsfd.ussd.UssdMenu;

public class OutDialer extends Thread {

	private String Username="";
	private String Password="";
	private String Server="localhost";
	private int Port=13000;
	private String Channelprefix="";
	private String SipServerAddress="";
	private CookieManager manager ;
	private String toNumber="";
	private String fromNumber="";
	private String AgiScript="";
	private String Param1="";
	private String Param2="";
	private String Param3="";
	private String Param4="";
	private String Param5="";
	
	public OutDialer (SystemParams sysparams)  throws SQLException{
		
		Username=sysparams.getParameter("AMI User Name");
		Password=sysparams.getParameter("AMI Password");
		Server=sysparams.getParameter("AMI Server");
		Port=Integer.parseInt(sysparams.getParameter("AMI Port"));
		Channelprefix=sysparams.getParameter("AMI OB Call Channel Prefix");
		SipServerAddress=sysparams.getParameter("SIP Server Address");
		
		manager = new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(manager);
        
	}
	

		
	public  void  setSearchParams(String toNumber, String fromNumber,String agiscript, String param1,String param2,String param3,String param4,String param5){
		this.AgiScript=agiscript;
		this.toNumber=toNumber;
		this.fromNumber=fromNumber;
		this.Param1=param1;
		this.Param2=param2;
		this.Param3=param3;
		this.Param4=param4;
		this.Param5=param5;
	    		
	}
	
	

	public  AMIResponse  authenticateAMI(String toNumber) throws IOException, URISyntaxException{
		String ActionID=toNumber+"-login-"+( new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
		String urlstring=  "http://"+Server+":"+Port+"/asterisk/rawman?action=login&username="+Username+"&secret="+Password+"&actionid="+ActionID;
		URL url = new URL(urlstring);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		AMIResponse amiresp = new AMIResponse();
	    String resp="";
	    while (( resp=in.readLine())!=null){
	    	if (resp.contains("Response")){
	    		amiresp.setResponse( resp.split(": ")[1]);
	    	}
	    	else if (resp.contains("ActionID")){
	    		amiresp.setActionID( resp.split(": ")[1]);
	    	}
	    	else if (resp.contains("Message")){
	    		amiresp.setMessage( resp.split(": ")[1]);
	    	}
	    	
	    	resp="";
	    }
	    
	    
	    
	    return amiresp;
	    		
	}



	@Override
	public void run() {
		AMIResponse loginresp;
		try {
			loginresp = authenticateAMI(toNumber);
			if (loginresp.getResponse().equalsIgnoreCase("Success")){
				String ActionID=toNumber+"-Originate-"+( new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());			
				String urlstring=  "http://"+Server+":"+Port+"/asterisk/rawman?action=Originate&Channel="+Channelprefix+toNumber+"&Priority=1&Timeout=60000&Context=default&Application=AGI&Data="+AgiScript+","+URLEncoder.encode(Param1, "UTF-8")+","+URLEncoder.encode(Param2, "UTF-8")+","+URLEncoder.encode(Param3, "UTF-8")+","+URLEncoder.encode(Param4, "UTF-8")+","+URLEncoder.encode(Param5, "UTF-8")+"&Callerid="+fromNumber+"&Variable="+URLEncoder.encode("__SIPADDHEADER51=P-Asserted-Identity: <sip:"+fromNumber+"@"+SipServerAddress+";user=deepcee>","UTF-8")+"&actionid="+ActionID;
				URL url = new URL(urlstring);
		        URLConnection connection = url.openConnection();
		        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				AMIResponse amiresp = new AMIResponse();
			    String resp="";
			    while (( resp=in.readLine())!=null){
			    	if (resp.contains("Response")){
			    		amiresp.setResponse( resp.split(": ")[1]);
			    	}
			    	else if (resp.contains("ActionID")){
			    		amiresp.setActionID( resp.split(": ")[1]);
			    	}
			    	else if (resp.contains("Message")){
			    		amiresp.setMessage( resp.split(": ")[1]);
			    	}
			    	
			    	resp="";
			    }
			}
		} catch (IOException | URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
